
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <event.h>
#include <pthread.h>

#include <librally.h>


typedef struct {
	int fd_svr;
	struct sockaddr_in addr_svr;
	struct event_base *evb;
	struct event	hb;
	struct event	cmd;
	struct timeval tv_hb;
} Global;

Global global;

void global_init()
{
	global.addr_svr.sin_family = AF_INET;
	global.addr_svr.sin_family = AF_INET;
	global.addr_svr.sin_port = htons(8888);
	global.addr_svr.sin_addr.s_addr = inet_addr("127.0.0.1");
	memset(&global.addr_svr.sin_zero, 0, 8);

	global.evb = event_init();
	global.tv_hb.tv_sec = 5;
}

void manager(int fd, short event, void *arg)
{
	char *sendmsg = "Test";
	Err err;
	
	err = rp_comm_send(global.fd_svr, sendmsg, 8);
	/*	re-install the timer	  */
	if (evtimer_add(&global.hb, &global.tv_hb) < 0)
	{
		return;
	}
	return;	
}

void cmd(int fd, short event, void *arg)
{
	char recvmsg[8];
	Err err;
	
	err = rp_comm_recv(global.fd_svr, recvmsg, 8);
	printf("msg = %s\n", recvmsg);
}

int main()
{
	Err err;
	
	global_init();

	/*	Add timer event	*/
	evtimer_set(&global.hb, manager, NULL);
	event_base_set(global.evb, &global.hb);
	if (evtimer_add(&global.hb, &global.tv_hb) < 0)
	{
		exit(127);
	}

	/* connect with server */ 
	err = rp_comm_tcp_client_init(&global.fd_svr, &global.addr_svr);
	event_set(&global.cmd, global.fd_svr, EV_READ|EV_PERSIST, cmd, NULL);
	event_base_set(global.evb, &global.cmd);
	if (event_add(&global.cmd, NULL) < 0)
	{
		exit(127);
	}
	
	event_base_dispatch(global.evb);
	
	close(global.fd_svr);
		
	exit(0);
}

